var utils = require('./exports/utils')
var constant = require('./exports/constant')
var point_map = require('./exports/point_map')
var ad_util = require('./exports/ad_util')
var ocrUtils = require('./exports/ocrUtils')
var treasure = {
  go_page_from_home() {
    if (
      !!utils.exists_text("百度") &&
      !!utils.exists_text("视频") &&
      !!utils.exists_text("小说")
    ) {
      console.log("treasure:go_page_from_home");
      utils.click_point.apply(
        utils,
        utils.get_size_point(point_map["首页任务"])
      );
      sleep(constant.min_click_after_time * 1000);
      this.start();
    } else {
      console.log("treasure:go_page_from_home: NOT FOUND");
    }
  },
  start() {
    var ad_texts = ["再看一个领取", "观看视频再得", "看广告再"];
    for (var i = 0; i < ad_texts.length; i++) {
      var content = ad_texts[i];
      var ui_text = utils.exists_text_starts_with(content);
      if (ui_text) {
        console.log("treasure start: 找到【" + content + "】" + ui_text.text());
        var gold = utils.get_gold(ui_text.text());
        console.log("treasure start: " + gold + "金币");
        if (gold >= constant.min_gold) {
          utils.click_text_starts_with(content);
          sleep(constant.min_click_after_time * 1000);
          ad_util.execute();
          this.next();
          return;
        } else {
          console.log("treasure start: 金币数量 --" + gold + "-- 太少，跳过");
          utils.click_point.apply(
            utils,
            utils.get_size_point(point_map["进入任务之后的关闭"])
          );
          sleep(constant.min_click_after_time * 1000);
          this.next();
          return;
        }
      }
    }
    console.log(
      "treasure start: 没找到 " +
        ad_texts
          .map(function (i) {
            return "--" + i + "--";
          })
          .join("或者")
    );
    if (utils.click_text("立即收下")) {
      console.log("treasure start: 找到【立即收下】");
      sleep(constant.min_click_after_time * 1000);
    }
    if (utils.click_text("开心收下")) {
      console.log("treasure start: 找到【开心收下】");
      sleep(constant.min_click_after_time * 1000);
    }
    var ui_text = utils.click_text("开宝箱得金币");
    if (ui_text) {
      console.log("treasure start: 找到【开宝箱得金币】");
      sleep(constant.min_click_after_time * 1000);
      this.init();
    } else {
      console.log("treasure start: 没找到【开宝箱得金币】");
    }
  },
  init() {
    console.log("treasure init:");
    this.start();
  },
  next() {
    console.log("treasure next");
    if (utils.click_text("开心收下")) {
      console.log("treasure next: 找到【开心收下】");
      sleep(2 * 1000);
      return;
    }
    if (utils.click_text("立即收下")) {
      console.log("treasure next: 找到【立即收下】");
      sleep(2 * 1000);
      return;
    }
    this.start();
  },
};

module.exports = treasure